package top.infopub.mgr.bpa.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.infopub.dto.bpa.BpaPublicProInfoDto;
import top.infopub.dto.bpa.EffectPlanChargedDetailDto;
import top.infopub.enums.bpa.BpaProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.bpa.dao.EffectPlanChargedDao;
import top.infopub.mgr.bpa.dao.EffectPlanChargedDetailDao;
import top.infopub.mgr.bpa.domain.EffectPlanChargedDomain;
import top.infopub.mgr.bpa.jsonVo.BizEffectChargedDetailJsonVo;
import top.infopub.mgr.bpa.service.BpaProcessManageService;
import top.infopub.mgr.bpa.service.EffectPlanChargedService;
import top.infopub.mgr.bpa.vo.EffectPlanPublicVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.dao.ProjectInfoDao;
import top.infopub.mgr.mkt.service.ProjectInfoService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.util.FileAttrUtils;
import top.infopub.model.bpa.EffectPlanCharged;
import top.infopub.model.bpa.EffectPlanChargedDetail;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 创效激励兑换
 */
@Service
public class EffectPlanChargedServiceImpl extends GenericServiceImpl<EffectPlanCharged, String> implements EffectPlanChargedService {

    @Autowired
    private EffectPlanChargedDao effectPlanChargedDao;
    @Autowired
    private EffectPlanChargedDetailDao effectPlanChargedDetailDao;
    @Autowired
    private ProjectInfoDao projectInfoDao;
    @Autowired
    private SetupProService setupProService;
    @Autowired
    private ProjectInfoService projectInfoService;
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;
    @Autowired
    private OAFlowService oaFlowService;
    @Autowired
    private BpaProcessManageService bpaProcessManageService;
    @Override
    public Page<EffectPlanChargedDomain> selectPageByDomainWhere(Page<EffectPlanChargedDomain> page, EffectPlanPublicVo effectPlanPublicVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        Page<EffectPlanChargedDomain> pageList = new Page<EffectPlanChargedDomain>();
        pageList = effectPlanChargedDao.selectListByDomainWhere(effectPlanPublicVo);
        return pageList;
    }

    @Override
    public BizEffectChargedDetailJsonVo getDetail(String id) {
        //判断id是否为空 如果为空则表示是新增 不为空表示是详情页面
        BizEffectChargedDetailJsonVo bizEffectChargedDetailJsonVo = new BizEffectChargedDetailJsonVo();
        if(StringUtils.isBlank(id)){
            bizEffectChargedDetailJsonVo = addDetailReturnData(bizEffectChargedDetailJsonVo);
        }else {
            bizEffectChargedDetailJsonVo = detailReturnData(id, bizEffectChargedDetailJsonVo);
        }
        return bizEffectChargedDetailJsonVo;
    }

    @Override
    public RspVo save(BizEffectChargedDetailJsonVo detailJson, Integer submitType, AuthorizationVO vo) {
        EffectPlanChargedDetailDto effectPlanChargedDetailDto = detailJson.getInfo();
        EffectPlanCharged effectPlanCharged = detailJson.getEffectPlanCharged();
        EffectPlanCharged effectPlanChargedDto = new EffectPlanCharged();
        BeanUtils.copyProperties(effectPlanCharged, effectPlanChargedDto);
        effectPlanChargedDto.setUptBy(vo.getId());
        effectPlanChargedDto.setUptTime(new Date());
        if(StringUtils.isBlank(effectPlanCharged.getId())){
            //新增
            effectPlanChargedDto.setAddBy(vo.getId());
            effectPlanChargedDto.setAddTime(new Date());
            effectPlanChargedDto.setCodes(IdFactory.getUUIDUpper());
            effectPlanChargedDto.setMemo("");
            effectPlanChargedDao.insertSelective(effectPlanChargedDto);
        }else{
            //校验商业策划数据是否存在
            EffectPlanCharged effectPlanChargedVo = effectPlanChargedDao.selectByPrimaryKey(effectPlanCharged.getId());
            if (effectPlanChargedVo == null) return RspVo.getFailureResponse(400, "商业策划详情不存在");
            //判断审批状态
            if (StringUtils.isNotBlank(effectPlanChargedVo.getProcessStatus())
                    && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), effectPlanChargedVo.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), effectPlanChargedVo.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            //更新
            effectPlanChargedDao.updateByIdSelective(effectPlanChargedDto);
            effectPlanChargedDto.setOaId(effectPlanChargedVo.getOaId());//预留给OA流程id
        }

        //子表
        addEffectPlanChargedDetail(detailJson, effectPlanChargedDto.getId());

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(detailJson.getFileAtt()!=null){
            String[] fileAtt = detailJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = FileAttrUtils.createProjectFileAtta(effectPlanChargedDto.getId(), file);
                attachmentList.add(attachment);
            }
        }
        projectAttachmentDao.deleteByWhere(effectPlanChargedDto.getId(), ProjectFileTypeEnum.FILE_TYPE140.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }

        //提交流程
        if (1 == submitType) {
            //TODO 有可能在同一个事务里面获取不到 budgetBatchVO 比如新增的时候获取这个
            if (StringUtils.isNotBlank(effectPlanChargedDto.getOaId())) {
                oaFlowService.finishOA(effectPlanChargedDto.getOaId());
            }
            BizEffectChargedDetailJsonVo bizEffectChargedDetailJsonVo = getDetail(effectPlanChargedDto.getId());
            String json = JSON.toJSONString(bizEffectChargedDetailJsonVo);
            bpaProcessManageService.sendProcess(BpaProcessDetailTypeEnum.PRO_NODE_TYPE35, json, effectPlanChargedDto.getId(), effectPlanChargedDto.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }

    //新增子表
    private void addEffectPlanChargedDetail(BizEffectChargedDetailJsonVo detailJson,String id){
        List<EffectPlanChargedDetail> list = detailJson.getEffectPlanChargedDetail();
        effectPlanChargedDetailDao.deleteByParentId(id);
        for(EffectPlanChargedDetail effectPlanChargedDetail: list){
            effectPlanChargedDetail.setParentId(id);//主表id
            effectPlanChargedDetailDao.insertSelective(effectPlanChargedDetail);
        }
    }

    //新增的数据封装返回
    public BizEffectChargedDetailJsonVo addDetailReturnData(BizEffectChargedDetailJsonVo bizEffectChargedDetailJsonVo){
        //返回所有的项目code和name
        bizEffectChargedDetailJsonVo.setProInfoList(setupProService.queryPublicProInfo());
        //返回审批人和审批日期
        EffectPlanCharged effectPlanCharged = new EffectPlanCharged();
        effectPlanCharged.setAuditTime(new Date());
        effectPlanCharged.setAddBy("");//TODO
        bizEffectChargedDetailJsonVo.setEffectPlanCharged(effectPlanCharged);
        return bizEffectChargedDetailJsonVo;
    }

    //查看详情的数据返回
    public BizEffectChargedDetailJsonVo detailReturnData(String id, BizEffectChargedDetailJsonVo bizEffectChargedDetailJsonVo){
        //主表信息
        EffectPlanCharged effectPlanCharged =  effectPlanChargedDao.selectByPrimaryKey(id);

        //项目的基础信息
        BpaPublicProInfoDto  dto = projectInfoService.queryBpaProInfoByProCode(effectPlanCharged.getProCode());
        EffectPlanChargedDetailDto info = new EffectPlanChargedDetailDto();
        info.setId(id);
        info.setApplyCompName(dto.getApplyCompName());
        info.setApplyDeptName(dto.getApplyDeptName());
        info.setApplyStaffName(dto.getApplyStaffName());
        info.setAreaCompName(dto.getAreaCompName());
        info.setCoopName(dto.getCoopName());
        info.setProCode(dto.getProCode());
        info.setProName(dto.getProName());
        info.setProCompName(dto.getProCompName());
        info.setProStaffName(dto.getProStaffName());
        info.setSgCityName(dto.getSgCityName());
        info.setProStaffName(dto.getProStaffName());
        bizEffectChargedDetailJsonVo.setInfo(info);
        //主表信息返回
        bizEffectChargedDetailJsonVo.setEffectPlanCharged(effectPlanCharged);
        //激励兑现金额明细
        List<EffectPlanChargedDetail> list = effectPlanChargedDetailDao.getEffectPlanChargedDetailList(id);
        bizEffectChargedDetailJsonVo.setEffectPlanChargedDetail(list);
        //下拉列表的数据
//        List<Map<String,String>> listMap = new ArrayList<>();
//        Map<String,String> map = new HashMap<>();
//        map.put(dto.getProCode(), dto.getProName());
//        listMap.add(map);
//        bizEffectChargedDetailJsonVo.setProNameAndId(listMap);

        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(id, ProjectFileTypeEnum.FILE_TYPE165.getCode(), null);
        bizEffectChargedDetailJsonVo.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));

        return bizEffectChargedDetailJsonVo;
    }

    @Override
    public GenericDao<EffectPlanCharged, String> getDao() {
        return effectPlanChargedDao;
    }
}
